package com.dogegg.lbblog.intercept;

import com.dogegg.lbblog.annotation.LogLabel;
import com.dogegg.lbblog.annotation.LogRecord;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;


public class SpringLogAnnotationParser implements LogAnnotationParser{

    @Override
    public LogRecordOperation parseLogAnnotation(Method method) {
        Set<LogRecord> allMergedAnnotations = AnnotatedElementUtils.findAllMergedAnnotations(method, LogRecord.class);
        if(allMergedAnnotations == null || allMergedAnnotations.isEmpty()){
            return null;
        }
        if(allMergedAnnotations.size() != 1){
            throw new IllegalStateException("MergedAnnotations required unique ");
        }
        LogRecord next = allMergedAnnotations.iterator().next();
        LogRecordOperation operation = new LogRecordOperation();
        operation.setCondition(next.condition());
        operation.setContent(next.content());
        operation.setSource(next.source());
        operation.setProcessor(next.processor());
        if(next.labels() != null){
            operation.setLabels(Arrays.stream(next.labels()).collect(Collectors.toMap(LogLabel::name,LogLabel::value)));
        }
        return operation;
    }
}
